<template>
  <div class="flex items-start gap-3 px-3 py-4">
    <!-- AI 头像 -->
    <el-avatar v-if="message.role === 'assistant'" :size="50"
      src='https://img.ixintu.com/download/jpg/201912/b205cf69d384225dea2d42a76c19f470.jpg!ys' class="flex-shrink-0" />

    <!-- 消息气泡 -->
    <div :class="[
      'max-w-[85%] rounded-lg px-4 py-2.5',
      message.role === 'user'
        ? 'bg-[#409EFF] text-white ml-auto'
        : 'bg-[#f4f4f5] text-gray-800'
    ]">
      <div v-if="message.role === 'user'" :class="['text-[14px] leading-relaxed text-white']">
        {{ message.content }}
      </div>
      <div v-else class="markdown-body" v-html="renderedContent" @click="handleCodeBlockClick" />
    </div>

    <!-- 用户头像 -->

    <el-avatar v-if="message.role === 'user'" :size="50" class="flex-shrink-0">
      user
    </el-avatar>
  </div>

  <!-- 新增的代码运行遮罩层（绝对定位，不影响原有样式） -->
  <div v-if="showCodeModal"
    style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:9999;display:flex;justify-content:center;align-items:center"
    @click="showCodeModal = false">
    <div style="width:80%;height:80%;background:#fff;border-radius:4px;padding:16px;display:flex;flex-direction:column"
      @click.stop>
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
        <div style="font-size:16px;font-weight:500">小工同学🤖</div>
        <button @click="showCodeModal = false"
          style="background:none;border:none;font-size:20px;cursor:pointer">&times;</button>
      </div>
      <iframe :srcdoc="currentCode" style="flex:1;border:none;background:#fff" sandbox="allow-scripts"></iframe>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import { ElMessage } from 'element-plus'
import type { Message } from '../types'
import 'highlight.js/styles/github.css'
import './markdown.css'

const props = defineProps<{
  message: Message
}>()

// 新增的状态变量
const showCodeModal = ref(false)
const currentCode = ref('')

// 保持原有的markdown-it配置
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        const code = hljs.highlight(str, { language: lang }).value
        return `<div class="code-block-wrapper">
                  <div class="code-block-header">
                    <span class="code-lang">${lang}</span>
                    <button class="copy-button" data-code="${encodeURIComponent(str)}">
                      <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-1"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>
                      复制
                    </button>
                    <button class="run-button" data-code="${encodeURIComponent(str)}">运行代码</button>
                  </div>
                  <pre><code class="hljs language-${lang}">${code}</code></pre>
                </div>`
      } catch (__) { }
    } 
    return `<pre><code class="hljs">${md.utils.escapeHtml(str)}</code></pre>`
  }
})

// 保持原有的渲染逻辑
const renderedContent = computed(() => {
  if (props.message.role === 'assistant') {
    return md.render(props.message.content)
  }
  return props.message.content
})

// 修改点击处理，添加运行代码逻辑
const handleCodeBlockClick = (e: MouseEvent) => {
  const target = e.target as HTMLElement

  if (target.classList.contains('copy-button')) {
    e.preventDefault()
    const code = decodeURIComponent(target.getAttribute('data-code') || '')
    copyToClipboard(code)
  }

  if (target.classList.contains('run-button')) {
    e.preventDefault()
    currentCode.value = decodeURIComponent(target.getAttribute('data-code') || '')
    showCodeModal.value = true
  }
}

// 保持原有的复制函数
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('代码已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败')
    console.error('复制失败:', err)
  }
}
</script>

<style>
/* 您原有的所有样式代码保持不变 */
.markdown-body {
  font-size: 14px;
  line-height: 1.6;
}

.markdown-body pre {
  background-color: #ffffff;
  border-radius: 6px;
  padding: 12px;
  margin: 8px 0;
  overflow-x: auto;
}

.markdown-body code {
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  font-size: 13px;
  padding: 2px 4px;
  border-radius: 3px;
}

.markdown-body p {
  margin: 8px 0;
}

.markdown-body ul,
.markdown-body ol {
  padding-left: 20px;
  margin: 8px 0;
}

.markdown-body table {
  border-collapse: collapse;
  width: 100%;
  margin: 8px 0;
}

.markdown-body th,
.markdown-body td {
  border: 1px solid #e5e7eb;
  padding: 8px;
  text-align: left;
}

.markdown-body th {
  background-color: #f9fafb;
}

.markdown-body a {
  color: #409EFF;
  text-decoration: none;
}

.markdown-body a:hover {
  text-decoration: underline;
}

.markdown-body blockquote {
  border-left: 4px solid #e5e7eb;
  margin: 8px 0;
  padding: 0 12px;
  color: #6b7280;
}

.markdown-body :not(pre)>code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 3px;
}

.code-block-wrapper {
  position: relative;
  margin: 1em 0;
  border-radius: 6px;
  background: #f6f8fa;
}

.code-block-header {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 2;
  display: flex;
  gap: 8px;
  align-items: center;
  opacity: 0;
  transition: opacity 0.2s;
}

.code-lang {
  font-size: 12px;
  color: #666;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
  background: rgba(255, 255, 255, 0.8);
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
}

.copy-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  color: #475569;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.copy-button:hover {
  background: #ffffff;
  border-color: #cbd5e1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  color: #1e293b;
}

.copy-button:active {
  transform: scale(0.98);
}

.code-block-wrapper:hover .code-block-header {
  opacity: 1;
}

.code-block-wrapper pre {
  margin: 0;
  padding: 2.5em 1em 1em;
  background: #f6f8fa;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  overflow-x: auto;
}

.code-block-wrapper pre code {
  padding: 0;
  background: transparent;
  border-radius: 0;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
  font-size: 13px;
  line-height: 1.6;
}

.code-block-wrapper pre::-webkit-scrollbar {
  height: 6px;
}

.code-block-wrapper pre::-webkit-scrollbar-track {
  background: transparent;
}

.code-block-wrapper pre::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 3px;
}

.code-block-wrapper pre::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

.hljs {
  counter-reset: line;
}

.markdown-body :not(pre)>code {
  background-color: rgba(175, 184, 193, 0.2);
  padding: 0.2em 0.4em;
  border-radius: 4px;
  font-size: 85%;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}

.code-block-wrapper pre code::selection,
.code-block-wrapper pre code *::selection {
  background: rgba(56, 139, 253, 0.15);
}
</style>